#!/bin/bash

# shellcheck source=meta-facebook/meta-harma/recipes-phosphor/gpio/phosphor-gpio-monitor/logging-util
source /usr/libexec/phosphor-gpio-monitor/logging-util

HELP="
Usage: thermal-event-logger <type> <gpio name>
<event> is the event type,
e.g. assert/deassert.

<gpio-name> is defined in json file,
e.g. cpu0-thermtrip-alert
"

# check if parameters are missing
if [[ -z "$1" || -z "$2" ]]; then
    echo "Missing required arguments: event type, gpio name."
    echo "$HELP"
    exit 1
fi

# get some parameters
GPIO_NAME=$2
case $1-$2 in
    assert-cpu0-thermtrip-alert)
    MSG_ID="xyz.openbmc_project.State.Thermal.DeviceOverOperatingTemperatureFault"
    ;;
    deassert-cpu0-thermtrip-alert | assert-cpu0-prochot-alert)
    MSG_ID="xyz.openbmc_project.State.Thermal.DeviceOverOperatingTemperature"
    ;;
    deassert-cpu0-prochot-alert)
    MSG_ID="xyz.openbmc_project.State.Thermal.DeviceOperatingNormalTemperature"
    ;;
    *)
    echo "Unrecognized event type or gpio name."
    exit 1
esac

DEVICE_PATH="/xyz/openbmc_project/State/Thermal/cpu0"
STASH_FILE="/run/${GPIO_NAME}.log_entry"

if check_valid_sgpio; then
    # This delay ensures the BMC does not receive abnormal events
    # during CMM/MB AC cycling or tray unplugging.
    # Such actions can cause the CPLD to lose power before the BMC,
    # leading to abnormal events being received.
    sleep 2
    case $1-$2 in
        assert-*)
            if [ ! -s "$STASH_FILE" ]; then
                    /usr/bin/log-create "$MSG_ID" --json \
                        "{ \"DEVICE\": \"${DEVICE_PATH}\", \"FAILURE_DATA\": \"${GPIO_NAME}\"}" \
                        > "${STASH_FILE}"
            fi
            ;;

        deassert-cpu0-thermtrip-alert)
            if [ -e "${STASH_FILE}" ]; then
                    log-resolve -p "$(< "${STASH_FILE}")" && rm "${STASH_FILE}"
            fi
            ;;

        deassert-cpu0-prochot-alert)
            if [ -e "${STASH_FILE}" ]; then
                log-resolve -p "$(< "${STASH_FILE}")" && rm "${STASH_FILE}"
            fi
            /usr/bin/log-create "$MSG_ID" --json \
                "{ \"DEVICE\": \"${DEVICE_PATH}\"}"
            ;;
        *)
            echo "Unrecognized thermal event."
            exit 1
    esac
else
    echo "Invalid sgpio."
fi
exit 0
